from typing import Optional, Union

from axiom_boot.di import service, conditional_on_setting, order
from axiom_boot.logging.setup import get_logger
from axiom_boot.scraper.exceptions import DownloadError
from axiom_boot.scraper.interfaces import ScraperMiddleware
from axiom_boot.scraper.models import Target, Response


logger = get_logger(__name__)


@order(10)
@service()
@conditional_on_setting(key="scraper__logging_enabled", expected_value=True)
class LoggingMiddleware(ScraperMiddleware):
    
    async def process_request(self, target: Target) -> Optional[Union[Target, Response]]:
        logger.info(f"请求发送 -> URL: {target.url}, Downloader: {target.downloader or 'default'}")
        return target

    async def process_response(self, target: Target, response: Response) -> Optional[Union[Target, Response]]:
        logger.info(
            f"收到响应 <- URL: {response.url}, "
            f"Status: {response.status_code}, "
            f"Content-Type: {response.headers.get('Content-Type', 'N/A')}"
        )
        return response

    async def process_exception(self, target: Target, exception: Exception) -> Optional[Union[Target, Response]]:
        if isinstance(exception, DownloadError):
            logger.error(f"下载失败 X  URL: {target.url}, 原因: {exception}")
        else:
            logger.error(f"处理异常 X  URL: {target.url}, 异常类型: {type(exception).__name__}, 原因: {exception}")
        return None 